package geppetto.phraseTable.resource;

import geppetto.phraseHMM.phraseExtraction.extractedphrase.data.ScoreData;
import geppetto.phraseTable.PhraseTable;
import geppetto.phraseTable.PhraseTableListenner;
import geppetto.phraseTable.PhraseTableListennerAdapter;
import geppetto.phraseTable.phrase.Phrase;
import gnu.trove.TIntDoubleHashMap;
import gnu.trove.TIntObjectHashMap;

public class SourceTargetIndexResource extends PhraseTableListennerAdapter{
	public TIntObjectHashMap<TIntObjectHashMap<TIntDoubleHashMap>> _sourcePhraseSums = new TIntObjectHashMap<TIntObjectHashMap<TIntDoubleHashMap>>();
	public TIntObjectHashMap<TIntObjectHashMap<TIntDoubleHashMap>> _targetPhraseSums = new TIntObjectHashMap<TIntObjectHashMap<TIntDoubleHashMap>>();
	protected final static String SCORE_HEADER = "score";

	@Override
	public void notifyNewPhrase(Phrase phrase) {
		TIntDoubleHashMap sourcePhrases = getPhrasesForSize(_sourcePhraseSums, phrase.getSourceLen(), phrase.getTargetLen());
		TIntDoubleHashMap targetPhrases = getPhrasesForSize(_targetPhraseSums, phrase.getSourceLen(), phrase.getTargetLen());
		if(!sourcePhrases.contains(phrase._sourcePhraseID)){
			sourcePhrases.put(phrase._sourcePhraseID, 0d);
		}
		Double score = ((ScoreData)phrase.getData(SCORE_HEADER)).getScore();
		sourcePhrases.put(phrase._sourcePhraseID, sourcePhrases.get(phrase._sourcePhraseID) + score);
		targetPhrases.put(phrase._targetPhraseID, targetPhrases.get(phrase._targetPhraseID) + score);
	}
	
	public TIntObjectHashMap<TIntObjectHashMap<TIntDoubleHashMap>> get_sourcePhraseSums() {
		return _sourcePhraseSums;
	}

	public void set_sourcePhraseSums(
			TIntObjectHashMap<TIntObjectHashMap<TIntDoubleHashMap>> phraseSums) {
		_sourcePhraseSums = phraseSums;
	}

	public TIntObjectHashMap<TIntObjectHashMap<TIntDoubleHashMap>> get_targetPhraseSums() {
		return _targetPhraseSums;
	}



	public void set_targetPhraseSums(
			TIntObjectHashMap<TIntObjectHashMap<TIntDoubleHashMap>> phraseSums) {
		_targetPhraseSums = phraseSums;
	}

	public static TIntDoubleHashMap getPhrasesForSize(TIntObjectHashMap<TIntObjectHashMap<TIntDoubleHashMap>> structure, int sourceSize, int targetSize){
		TIntObjectHashMap<TIntDoubleHashMap> targetArray = structure.get(sourceSize);
		if(targetArray==null){
			targetArray = new TIntObjectHashMap<TIntDoubleHashMap>();
			structure.put(sourceSize, targetArray);
		}
		TIntDoubleHashMap phrases = targetArray.get(targetSize);
		if(phrases == null){
			phrases = new TIntDoubleHashMap();
			targetArray.put(targetSize, phrases);
		}
		return phrases;
	}

	@Override
	public void loadPhrasesComplete(PhraseTable table) {
		_sourcePhraseSums.compact();
		_targetPhraseSums.compact();
	}

}
